package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;
    @Autowired
    private WmNewsAutoScanService autoScanService;

    /**
     * 添加任务到延迟队列中
     *
     * @param wmNews
     */
    @Override
    @Async
    public void addWmNewsToTask(WmNews wmNews) {
        Task task = new Task();
        task.setExecuteTime(wmNews.getPublishTime().getTime());

        WmNews dataNews = new WmNews();
        dataNews.setId(wmNews.getId());
        task.setParameters(ProtostuffUtil.serialize(dataNews));
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());

        scheduleClient.addTask(task);

        log.info("添加任务到延迟服务当中---end");
    }

    /**
     * 消费延迟队列数据
     */
    @Scheduled(fixedRate = 1000)
    @Override
    public void scanNewsByTask() throws Exception {
        log.info("文章审核---消费任务执行---start");
        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if(null != responseResult && responseResult.getCode() == 200){
            Object data = responseResult.getData();
            if(null != data){
                Task task = JSON.parseObject(data.toString(), Task.class);
                byte[] parameters = task.getParameters();
                WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);

                // 审核文章
                autoScanService.autoScanWmNews(wmNews.getId());

                log.info("文章审核---消费任务执行---end---文章id: " + wmNews.getId());
            }
        }
        log.info("文章审核---消费任务执行---end");
    }
}
